<?php
namespace App\HttpController;

//use App\Models\UserModel;
use App\Models\User;
use EasySwoole\Validate\Validate;
use App\Exceptions\TestException;
use App\Exceptions\ParamException;

class Index extends BaseController
{

    function index()
    {
        throw new ParamException('参数有误');
        $this->writeJson(200, TestException::add(1,3));
        //$this->writeJson(200, User::all());
        /* $this->response()->write(); */
    }

    public function create()
    {
        $req = $this->request();
        try{
            $name = $req->getRequestParam('name');
            $email = $req->getRequestParam('email');
            $password = $req->getRequestParam('password');

            $user = [
                'name' => $name,
                'email' => $email,
                'password' => $password,
            ];
            User::create($user);
        }catch(\Exception $e){
            $this->writeJson(502, $e->getMessage());
        }
    }

    protected function actionNotFound(?string $action)
    {
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';
        if(!is_file($file)){
            $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html';
        }
        $this->response()->write(file_get_contents($file));
    }

    protected function validateRule(?string $action): ?Validate
    {
        $v = new Validate();
        switch($action) {
            case 'create':
                $v->addColumn('name', '姓名')->required('不能为空');
                $v->addColumn('email', '邮箱')->required('不能为空');
            break;
        }
        return $v;
    }

    
}